#! /bin/bash
scriptname=`basename $0`
pk8="platform.pk8"
pem="platform.x509.pem"
out="keystore.jks"

# informations should be passed by argument.
alias=""
keystorepass=""
keypass=""

usage() {
cat << EOF
usage: ${scriptname} [-k keystore pass] [-p key pass] [-a key alias]
This script is used to import ${pem} and ${pk8} into a Java Key Store.
EOF
}

while [ $# -gt 0 ]; do
	case $1
  		in
			-k)
				keystorepass=$2
				shift 2
		;;
			-p)
				keypass=$2
				shift 2
		;;
			-a)
				alias=$2
				shift 2
		;;
			-h | help | -help | --help)
				usage
				exit 0
		esac
done

if [ -z ${alias} ] | [ -z ${keystorepass} ] | [ -z ${keypass} ]; then
	echo "${scriptname}: Missing informations..." 1>&2
	usage
	exit 1
fi

for f in "${pk8}" "${pem}"; do
	if [ ! -f "$f" ]; then
		echo "${scriptname}: Can't find file $f..." 1>&2
		exit 1
	fi
done

if [ -e ${out} ]; then
  mv ${out} ${out}.$(date +%s).backup
fi

echo openssl pkcs8 -in ${pk8} -inform DER -outform PEM -out platform.priv.pem -nocrypt
openssl pkcs8 -in ${pk8} -inform DER -outform PEM -out platform.priv.pem -nocrypt

echo openssl pkcs12 -export -in ${pem} -inkey platform.priv.pem -out platform.pk12 -name ${alias} -password pass:${keystorepass}
openssl pkcs12 -export -in ${pem} -inkey platform.priv.pem -out platform.pk12 -name ${alias} -password pass:${keystorepass}

echo keytool -J-Duser.language=en -importkeystore -destkeystore ${out} -srckeystore platform.pk12 -srcstoretype PKCS12 -deststorepass ${keystorepass} -srcstorepass ${keystorepass}
keytool -J-Duser.language=en -importkeystore -destkeystore ${out} -srckeystore platform.pk12 -srcstoretype PKCS12 -deststorepass ${keystorepass} -srcstorepass ${keystorepass}

echo keytool -J-Duser.language=en -keypasswd -keystore ${out} -alias ${alias} -storepass ${keystorepass} -new ${keypass}
keytool -J-Duser.language=en -keypasswd -keystore ${out} -alias ${alias} -storepass ${keystorepass} -new ${keypass}

rm platform.priv.pem
rm platform.pk12
